import { getCurrentInstance, ref, reactive } from "vue";
import dayjs from "dayjs";
import { PageVo, Teacher, TeacherQueryVo } from "@api/model";
import { listPage } from "@api/teacher";

// 查询表单的数据类型
interface TeacherSearchForm {
    name: string;
    level: number;
    createTimeRange: string[];
    page?: number;
    pageSize?: number;
  }
  
  // 查询表单的响应式数据
  const searchForm = reactive<TeacherSearchForm>({
    // 姓名
    name: null,
    // 头衔
    level: null,
    // 添加时间
    createTimeRange: [],
    // 页面
    page: 1,
    // 页面大小
    pageSize: 5,
  });
  
  // 查询结果的响应式数据
  // 表格数据
  const tableData = ref<Teacher[]>([]);
  // 表格加载标识
  let tableLoading = ref(false);
  // 记录总数
  let total = ref(0);
  
  export default function teacherSearch() {
    // 查询
    const instance = getCurrentInstance();
    function handleSearch() {
      searchForm.page = 1;
      searchForm.createTimeRange = searchForm.createTimeRange?.map((d) => {
        return dayjs(d).format("YYYY-MM-DD");
      });
      getTeacherDataList();
    }
  
    // 重置查询表单
    function resetSearchForm() {
      //eslint-disable-next-line
      // 获得表单引用 instance?.refs.searchFormRef
      // 还可以使用响应式数据获得表单引和
      (instance?.refs.searchFormRef as any).resetFields();
      searchForm.page = 1;
      searchForm.pageSize = 5;
      getTeacherDataList();
    }
  
    // 访问后台服务
    function getTeacherDataList() {
      // 构造请求数据
      const teacherQueryVo: TeacherQueryVo = {
        name: searchForm.name,
        level: searchForm.level,
        beginDate: searchForm.createTimeRange[0],
        endDate: searchForm.createTimeRange[1],
      };
  
      // 开始加载
      tableLoading.value = true;
      // 分页查询
      listPage(searchForm.page ?? 1, searchForm.pageSize ?? 5, teacherQueryVo)
        .then((result: PageVo<Teacher>) => {
          console.log(result)
          // 停止加载
          tableLoading.value = false;
          // 加载分页数据
          tableData.value = result.data.dataList;
          // 记录总数
          total.value = result.data.total;
        })
        .catch((err:any) => {
          console.log(err);
          // 出错后要清除标识
          tableLoading.value = false;
        });
    }
  
    // 页面更改
    function handleCurrentPageChange(val: number) {
      searchForm.page = val;
      getTeacherDataList();
    }
  
    // 页面大小更改
    function handlePageSizeChange(val: number) {
      searchForm.pageSize = val;
      getTeacherDataList();
    }
  
    return {
      searchForm,
      handleSearch,
      resetSearchForm,
      getTeacherDataList,
      tableData,
      tableLoading,
      total,
      handleCurrentPageChange,
      handlePageSizeChange,
    };
  }